<template>
  <div>
    <div class="search-container" @click="sendMessageToMiniProgram">
      <input readonly type="text" class="search-input" placeholder="请输入地点...">
      <div class="search-btn">搜索</div>
      <!--      <button @click="sendMessageToMiniProgram">发送消息给小程序</button>-->
    </div>

    <div class="floor-selector" @click.stop>
      <div class="floor-list">
        <div
            v-for="select in select1"
            :key="select"
            :class="['floor-item', selected === select ? 'active' : '']"
            @click="toggleList(select)"
        >
          {{ select }}<span class="arrow">›</span>
        </div>
      </div>


      <div class="building-popup" v-if="showFloors">
        <div class="building-scroll">
          <div
              v-for="floor in floors || []"
              :key="floor"
              class="building-item"
              @click="selectFloor(floor)"
          >
            {{ floor }}
          </div>
        </div>
      </div>

      <div class="building-popup" v-if="showBuildings">
        <div class="building-scroll">
          <div
              v-for="building in buildings || []"
              :key="building"
              class="building-item"
              @click="selectBuilding(building)"
          >
            {{ building }}
          </div>
        </div>
      </div>


    </div>

    <!--    <view v-if="selectedPlaceConfirm" class="place-card">-->
    <!--      <view class="actions">-->
    <!--        &lt;!&ndash;        <button class="action-button" open-type="collect">&ndash;&gt;-->
    <!--        &lt;!&ndash;          <img src="@/assets/icons/收藏.png" class="icon"/>&ndash;&gt;-->
    <!--        &lt;!&ndash;          查看&ndash;&gt;-->
    <!--        &lt;!&ndash;        </button>&ndash;&gt;-->
    <!--        <view class="place-name">{{ selectedPlace.name }}</view>-->
    <!--        <button class="action-button" @click="navigateToLocation">-->
    <!--          <img src="@/assets/icons/导航.png" class="icon"/>-->
    <!--          去这里-->
    <!--        </button>-->
    <!--      </view>-->
    <!--    </view>-->

    <button class="navigation" @click="navigateTo">
      <img src="@/assets/导航栏.png"/>
    </button>

    <div id="map"></div>
    <!--    <img style="margin-left:300px;height: 500px;width: 300px" :src="imageShow">-->

  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import imageUrl from '@/assets/A1.png';
import {baseUrlApi} from '/src/utils/url.js'

//import imageUrl1 from '@/assets/背景.jpg';

// import 'leaflet-routing-machine'
const sendMessageToMiniProgram = () => {
  if (window.wx && window.wx.miniProgram) {
    wx.miniProgram.navigateTo({url: '/pages/history/index/index'})
    // wx.miniProgram.postMessage({
    //   data: {
    //     type: 'webButtonClick',
    //     message: '搜索'
    //   }
    // })
    // alert('消息已发送到小程序')
  } else {
    alert('不在微信小程序环境，无法通信')
  }
}

const select1 = ["楼层", "座"]
const floors = ['F1', 'F2', 'F3', 'F4', 'F5']
const buildings = ['A座', 'B座', 'C座', 'D座', 'E座', 'F座', 'G座',]


const selected = ref('')
const selectedFloor = ref('F1')
const selectedBuilding = ref('A座')

const showFloors = ref(false)
const showBuildings = ref(false)

function toggleList(select) {
  if (selected.value === select) {
    if (showBuildings.value) {
      showBuildings.value = false
    }
    if (showFloors.value) {
      showFloors.value = false
    }
    selected.value = ''
    return
  }
  selected.value = select
  if (select === "座") {
    showFloors.value = false;
    showBuildings.value = true;
  } else if (select === "楼层") {
    showBuildings.value = false;
    showFloors.value = true;
  }
}

const imageShow = ref()
const imageWidth = ref()
const imageHeight = ref()

function selectFloor(floor) {
  selectedFloor.value = floor
  showFloors.value = false
  const a = floor.charAt(1)
  fetch(baseUrlApi("images/view" + "?name=" + a), {
    method: 'GET',
  }).then(response => response.json()).then(result => {
    imageShow.value = result.data

    async function loadImageSize() {
      try {
        if (imageOverlay) {
          map.removeLayer(imageOverlay);
        }
        const size = await getImageSize(imageShow.value);
        imageWidth.value = size.width;
        imageHeight.value = size.height;
        const bounds = [[0, 0], [imageHeight.value, imageWidth.value]]
        const bounds1 = [[-350, -350], [imageHeight.value + 350, imageWidth.value + 350]]
        map.setMaxBounds(bounds1)
        imageOverlay = L.imageOverlay(imageShow.value, bounds).addTo(map)
        // map.fitBounds(bounds)
        setTimeout(() => {
          selectBuilding("G座")
        }, 300);
      } catch (err) {
        console.error(err);
      }
    }

    loadImageSize();
  })
}


function selectBuilding(building) {
  fetch(baseUrlApi("navigation/getCenter" + "?floor=" + building.charAt(0) + selectedFloor.value.toString().charAt(1)), {
    method: 'GET',
  }).then(response => response.json()).then(result => {
    const newZoom = Math.min(-1.8, map.getMaxZoom()); // 防止超过最大缩放
    const latlng = L.latLng(imageHeight.value - result.data.y, result.data.x); // 你的目标坐标
    console.log(latlng, newZoom)
    map.flyTo(latlng, newZoom);
  })
}


function getImageSize(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    // img.crossOrigin = 'anonymous'; // 可选：跨域图片时建议加上
    img.src = url;
    img.onload = function () {
      resolve({
        width: img.width,
        height: img.height
      });
    };

    img.onerror = function () {
      reject(new Error('图片加载失败: ' + url));
    };
  });
}

let map
let imageOverlay
const placeNow = ref("A101")

onMounted(() => {
  map = L.map('map', {
    crs: L.CRS.Simple,
    minZoom: -10,
    maxZoom: 10,
    zoomSnap: 0.1,
    attributionControl: false,
  })

  fetch(baseUrlApi("images/view" + "?name=" + 1), {
    method: 'GET',
  }).then(response => response.json()).then(result => {
    console.log('图片地址:', result); // 取出 data 字段里的图片链接
    imageShow.value = result.data

    async function loadImageSize() {
      try {
        const size = await getImageSize(imageShow.value);
        imageWidth.value = size.width;
        imageHeight.value = size.height;
        console.log(imageWidth.value + "  " + imageHeight.value)
        const bounds = [[0, 0], [imageHeight.value, imageWidth.value]]
        const bounds1 = [[-500, -500], [imageHeight.value + 500, imageWidth.value + 500]]
        map.setMaxBounds(bounds1)
        imageOverlay = L.imageOverlay(imageShow.value, bounds).addTo(map)
        map.fitBounds(bounds)
        setTimeout(() => {
          selectBuilding("G座")
        }, 300);
      } catch (err) {
        console.error(err);
      }
    }

    loadImageSize();
  })

  map.on('click', function (e) {
    const latlng = e.latlng;


    const lat = Number(e.latlng.lat.toFixed(0));
    const lng = Number(e.latlng.lng.toFixed(0));
    console.log('点击坐标：', lat, lng);
    const y = imageHeight.value - lat
    const x = lng
    const floor = selectedFloor.value.toString().charAt(1)
    fetch(baseUrlApi("navigation/touch" + "?floor=" + floor + "&x=" + x + "&y=" + y), {
      method: 'GET',
    }).then(response => response.json()).then(result => {
      const data = result.data[0]
      placeNow.value = data.nodeName
      if (placeNow.value != null) {
        const popupContent = `
  <div style="display: flex; align-items: center;  font-size: 14px;">
    <span style="font-weight: 600; color: #333;">${placeNow.value}</span>
    <button style="margin-left: 10px" id="popup-btn" class="action-button">去这里</button>
  </div>
  `;
        const popup = L.popup()
            .setLatLng(latlng)
            .setContent(popupContent)
            .openOn(map);

        setTimeout(() => {
          const btn = document.getElementById('popup-btn');
          if (btn) {
            btn.addEventListener('click', () => {
              if (window.wx && window.wx.miniProgram) {
                wx.miniProgram.navigateTo({
                  url: `/pages/place/index/index?name=${placeNow.value}`,
                });
              } else {
                alert('不在微信小程序环境，无法通信');
              }
            });
          } else {
            console.warn("popup button 未找到");
          }
        }, 0);
      }
    })
  });

  // async function loadImageSize() {
  //   try {
  //     const size = await getImageSize(imageUrl);
  //     imageWidth.value = size.width;
  //     imageHeight.value = size.height;
  //     console.log('宽:', imageWidth.value, '高:', imageHeight.value);
  //     const bounds = [[0, 0], [imageHeight.value, imageWidth.value]]
  //     const bounds1 = [[-200, -200], [imageHeight.value + 200, imageWidth.value + 200]]
  //     map.setMaxBounds(bounds1)
  //     imageOverlay = L.imageOverlay(imageUrl, bounds).addTo(map)
  //     map.fitBounds(bounds)
  //   } catch (err) {
  //     console.error(err);
  //   }
  // }
  //
  // loadImageSize();
  // L.control.scale().addTo(map)
})


// 点击外部关闭弹出框
onMounted(() => {
  document.addEventListener('click', () => {
    showBuildings.value = false
    showFloors.value = false
  })
})

function navigateTo(event) {
  const button = event.currentTarget
  const rect = button.getBoundingClientRect()
  const offsetX = event.clientX - rect.left
  const width = rect.width
  console.log('点击位置:', offsetX)
  if (offsetX < 100) {
    // if (window.wx && window.wx.miniProgram) {
    //   wx.miniProgram.navigateTo({url: '/pages/history/index/index'})
    // } else {
    //   alert('不在微信小程序环境，无法通信')
    // }
  } else if (offsetX < 210) {
    if (window.wx && window.wx.miniProgram) {
      wx.miniProgram.reLaunch({url: '/pages/findLatest/index/index'})
    } else {
      alert('不在微信小程序环境，无法通信')
    }
  } else if (offsetX < 320) {
    if (window.wx && window.wx.miniProgram) {
      wx.miniProgram.reLaunch({url: '/pages/collect/index/index'})
    } else {
      alert('不在微信小程序环境，无法通信')
    }
  } else {
    if (window.wx && window.wx.miniProgram) {
      wx.miniProgram.reLaunch({url: '/pages/login/index'})
    } else {
      alert('不在微信小程序环境，无法通信')
    }
  }
}


const selectedPlace = {name: '咖啡店', description: '提供咖啡、甜点和休闲环境。'}

</script>

<style>
#map {
  width: 100%;
  height: 80%;
  position: fixed;
  top: 65px;
  left: 0;
  z-index: 0; /* ✅ 不要为负数 */
  pointer-events: auto; /* ✅ 允许它响应拖动等事件 */
  background: white;
}

.search-container {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 20px;
  padding: 5px 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 2px solid #ccc;
}

.navigation {
  position: fixed; /* 固定定位 */
  bottom: 0px; /* 距离底部20px */
  left: 50%; /* 居中对齐 */
  transform: translateX(-50%); /* 水平居中 */
  background: none; /* 去掉按钮背景 */
  border: none; /* 去掉按钮边框 */
  padding: 0;
  margin: 0;
  z-index: 999; /* 保证在最上面 */
}

.search-input {
  border: none;
  outline: none;
  padding: 10px;
  font-size: 16px;
  flex: 1;
  background-color: transparent;
}

.search-btn {
  margin-left: 10px;
  color: red;
  font-weight: bold;
}

.floor-selector {
  z-index: 1;
  display: flex;
  position: fixed;
  top: 75%;
}

.floor-list {
  width: 60px;
  background-color: #f8f8f8;
  border-right: 1px solid #ddd;
}

.floor-item {
  padding: 10px;
  cursor: pointer;
}

.floor-item.active {
  background-color: #4caf50;
  color: white;
}

.arrow {
  float: right;
}

.building-popup {
  position: absolute;
  left: 60px;
  top: -160px;
  width: 60px;
  background-color: white;
  border-left: 1px solid #ddd;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  pointer-events: auto; /* 默认允许点击 */
}

.building-popup.hidden {
  display: none; /* ✅ 彻底移除元素 */
}


.building-scroll {
  max-height: 300px;
  overflow-y: auto;
}

.building-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.building-item:hover {
  background-color: #f0f0f0;
}


.place-card {
  position: fixed;
  bottom: 55px;
  left: 0;
  width: 100%;
  background: #fff;
  padding: 16px;
  box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.1);
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  z-index: 10; /* 高于地图 */
  box-sizing: border-box;
  max-height: 40vh;
  overflow-y: auto;
}

.place-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.place-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.actions {
  display: flex;
  justify-content: space-between;
}

.action-button {
  background-color: #409EFF;       /* 主色调：Element UI 蓝 */
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease, box-shadow 0.2s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);

}

.action-button:hover {
  background-color: #66b1ff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.action-button:active {
  background-color: #3a8ee6;
}

.icon {
  width: 15px;
  height: 15px;
  margin-right: 10rpx;
  display: inline-block;
}

</style>

